import { defineStore } from 'pinia'
import {
  accountLoginRequest,
  getUserMenusByRoleId
} from '@/service/login/login'
import type { IAccount } from '@/types'
import { localCache } from '@/utils/cache'
import { mapMenusToRoutes } from '@/utils/map-menus'
import router from '@/router'
import { LOGIN_TOKEN } from '@/global/constants'

interface ILoginState {
  token: string
  admin: any
  appcfg: any
  perList: any
  tokenInfo: any
  userMenus: any // 声明菜单
}

const useLoginStore = defineStore('login', {
  // 如何制定state的类型
  state: (): ILoginState => ({
    token: localCache.getCache(LOGIN_TOKEN) ?? '', // 有token则读取值，没有则默认空
    admin: localCache.getCache('admin') ?? {},
    appcfg: localCache.getCache('appcfg') ?? '',
    perList: localCache.getCache('perList') ?? [],
    tokenInfo: {},
    userMenus: []
  }),
  actions: {
    async loginAccountAction(account: IAccount) {
      // 1.账号登录, 获取token等信息
      const loginResult = await accountLoginRequest(account)
      console.log(loginResult)

      localCache.setCache(LOGIN_TOKEN, this.token)

      // 2.获取登录用户的详细信息(role信息)
      // const userInfoResult = await getUserInfoById(id)
      // const userInfo = userInfoResult.data
      // this.userInfo = userInfo
      let data = loginResult.data
      this.admin = data.admin
      this.tokenInfo = data.tokenInfo
      this.token = data.tokenInfo.tokenValue
      this.appcfg = data.appcfg
      this.perList = data.perList
      // 获取权限id
      const roleId = this.admin.roleId
      // 存储token
      localCache.setCache(LOGIN_TOKEN, this.token)

      // 3.根据角色请求用户的权限(菜单menus)
      const userMenusResult = await getUserMenusByRoleId(roleId)
      const userMenus = userMenusResult.data
      this.userMenus = userMenus

      // 4.进行本地缓存
      // localCache.setCache('userInfo', userInfo)
      localCache.setCache('admin', this.admin)
      localCache.setCache('appcfg', this.appcfg)
      localCache.setCache('perList', this.perList)
      localCache.setCache('userMenus', userMenus)

      // 重要: 动态的添加路由
      const routes = mapMenusToRoutes(userMenus)
      routes.forEach((route) => router.addRoute('main', route))

      // 5.页面跳转(main页面)
      router.push('/main')
    },

    loadLocalCacheAction() {
      // 1.用户进行刷新默认加载数据
      const token = localCache.getCache(LOGIN_TOKEN)
      const admin = localCache.getCache('admin')
      const userMenus = localCache.getCache('userMenus')
      if (token && admin && userMenus) {
        this.token = token
        this.userMenus = userMenus
        // 2.动态添加路由
        const routes = mapMenusToRoutes(userMenus)
        routes.forEach((route) => router.addRoute('main', route))
      }
    }
  }
})

export default useLoginStore
